#include "AudioPlayer.h"

// 预计算的波形缓冲区
int16_t precomputedWave[BUFFER_SIZE * CHANNELS];

// 构造函数
AudioPlayer::AudioPlayer() {
  volume = 0.2;         // 适中音量（可按需调整）
  playMode = 0;         // 默认停止播放
  lastPlayTime = 0;     // 上次播放时间
  playInterval = 0;     // 播放间隔
  waveIndex = 0;        // 波形数组索引
  initialized = false;  // 初始化状态
  
  // 预生成波形数据
  int waveSize = sizeof(di_wave) / sizeof(int16_t);
  for (int i = 0; i < BUFFER_SIZE; i++) {
    int16_t sample = (int16_t)(di_wave[i % waveSize] * volume);
    precomputedWave[i * 2] = sample;      // 左声道
    precomputedWave[i * 2 + 1] = sample;  // 右声道
  }
}

// 析构函数
AudioPlayer::~AudioPlayer() {
  if (initialized) {
    i2s_driver_uninstall(I2S_NUM_0);
    digitalWrite(AMP_SD, LOW);  // 关闭功放
  }
}

// 初始化函数
bool AudioPlayer::begin() {
  // 初始化功放
  pinMode(AMP_SD, OUTPUT);
  pinMode(AMP_GAIN, OUTPUT);
  digitalWrite(AMP_SD, HIGH);   // 开启功放
  digitalWrite(AMP_GAIN, LOW);  // 最低硬件增益

  // 初始化I2S
  initI2S();
  // 生成波形buffer
  generateWave();

  initialized = true;
  Serial.println("音频播放器初始化完成");
  return true;
}

// 循环函数
void AudioPlayer::loop() {
  if (!initialized) {
    return;
  }

  // 业务判断：如果是停止播放模式，将缓冲区填充为静音
  if (playMode == 0) {
    memset(audioBuffer, 0, BUFFER_SIZE * CHANNELS * sizeof(int16_t));
  } else {
    // 检查是否到达播放时间间隔
    unsigned long currentTime = millis();
    if (currentTime - lastPlayTime >= playInterval) {
      // 使用预计算的波形数据
      memcpy(audioBuffer, precomputedWave, BUFFER_SIZE * CHANNELS * sizeof(int16_t));
      lastPlayTime = currentTime;  // 更新上次播放时间
    } else {
      // 间隔期间保持静音
      memset(audioBuffer, 0, BUFFER_SIZE * CHANNELS * sizeof(int16_t));
    }
  }

  // 持续播放
  size_t bytesWritten;
  i2s_write(I2S_NUM_0, audioBuffer, BUFFER_SIZE * CHANNELS * sizeof(int16_t), &bytesWritten, portMAX_DELAY);
}

// 设置播放模式
void AudioPlayer::setPlayMode(int mode) {
  if (mode >= 0 && mode <= 3) {
    playMode = mode;
    if (playMode == 0) {
      Serial.println("已停止音频播放");
    } else {
      // 设置播放间隔
      if (playMode == 1) {
        playInterval = 500;  // 0.5秒
        Serial.println("循环播放波形数组(间隔0.5秒)");
      } else if (playMode == 2) {
        playInterval = 300;  // 0.3秒
        Serial.println("循环播放波形数组(间隔0.3秒)");
      } else if (playMode == 3) {
        playInterval = 100;  // 0.1秒
        Serial.println("循环播放波形数组(间隔0.1秒)");
      }
      waveIndex = 0;  // 重置波形索引
      // 设置为当前时间减去一个小值，确保立即开始播放
      lastPlayTime = 0;
    }
  }
}

// 设置音量
void AudioPlayer::setVolume(float vol) {
  if (vol >= 0.0 && vol <= 1.0) {
    volume = vol;
    Serial.printf("音量已设置为: %.2f\n", volume);
    
    // 如果已初始化，重新生成预计算的波形数据
    if (initialized) {
      generateWave();
    }
  }
}

// 获取当前播放模式
int AudioPlayer::getPlayMode() const {
  return playMode;
}

// 停止播放
void AudioPlayer::stop() {
  setPlayMode(0);
}

// 初始化I2S
void AudioPlayer::initI2S() {
  i2s_config_t i2s_config = {
    .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
    .sample_rate = SAMPLE_RATE,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
    .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
    .communication_format = I2S_COMM_FORMAT_STAND_I2S,
    .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
    .dma_buf_count = 8,
    .dma_buf_len = 128,
    .use_apll = true,
    .tx_desc_auto_clear = true,
    .fixed_mclk = 0
  };

  i2s_pin_config_t pin_config = {
    .bck_io_num = I2S_BCLK,
    .ws_io_num = I2S_LRC,
    .data_out_num = I2S_DOUT,
    .data_in_num = I2S_PIN_NO_CHANGE
  };

  i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
  i2s_set_pin(I2S_NUM_0, &pin_config);
  i2s_zero_dma_buffer(I2S_NUM_0);
}

// 生成波形数组的音频
void AudioPlayer::generateWave() {
  int waveSize = sizeof(di_wave) / sizeof(int16_t);
  for (int i = 0; i < BUFFER_SIZE; i++) {
    int16_t sample = (int16_t)(di_wave[i % waveSize] * volume);
    precomputedWave[i * 2] = sample;      // 左声道
    precomputedWave[i * 2 + 1] = sample;  // 右声道
  }
}